 package org.yf.samples.web;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.yf.samples.model.CommonMessageResultVO;
import org.yf.samples.model.ExamUserVO;
import org.yf.samples.model.User;
import org.yf.samples.service.IUserService;
import org.json.JSONObject;

@Controller
public class UserController {

	@Autowired
	private IUserService userService;
	
	@Autowired
	private LocaleResolver localeResolver;
	
	@ModelAttribute
	public User getUser(){
		return new User();
	}

	@RequestMapping(value = "/userChangeLocale")
	public String changeLocale(HttpServletRequest request, HttpServletResponse response, String localeType){
		if("en_US".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.US);
		}else if("zh_CN".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/users";
	}
	
	@RequestMapping("/users")
	public String Users(Model model){
		List<ExamUserVO> list = userService.findAllUsers();
		for(ExamUserVO user : list){
			if("0".equals(user.getGender())){
				user.setGender("男");
			}else if("1".equals(user.getGender())){
				user.setGender("女");
			}else{
				user.setGender("");
			}
		}
		model.addAttribute("userList", list);
		return "user/userList";
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String toAdd(Model model){
		model.addAttribute("user", new ExamUserVO());
		return "user/add";
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(RedirectAttributes redirectAttributes, @Validated ExamUserVO user, BindingResult result){
		if(result.hasErrors()){
			return "user/add";
		}
		try {
			user.setGender(user.getGender().substring(0,1));
			user.setPassword(user.getUserId());
			user.setEmail("123456@qq.com");
			user.setLastLockTime(new java.sql.Date(System.currentTimeMillis()));
			user.setLoginFailCount(0);
			userService.createUser(user);
			redirectAttributes.addFlashAttribute("message", "添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/users";
	}
	
	@ResponseBody
	@RequestMapping(value = "/studentAdd", method = RequestMethod.POST)
	public CommonMessageResultVO studentAdd(RedirectAttributes redirectAttributes, @Valid ExamUserVO user, BindingResult result){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
		if(result.hasErrors()){
			List<ObjectError> errorList = result.getAllErrors();
			for(ObjectError error : errorList){
				FieldError fe = (FieldError) error;
				messageMap.put(fe.getField(), fe.getDefaultMessage());
			}
			resultVO.setMessageMap(messageMap);
			return resultVO;
		}
		try{
			user.setPassword(user.getUserId());
			user.setLastLockTime(new java.sql.Date(System.currentTimeMillis()));
			user.setLoginFailCount(0);
			userService.createUser(user);
			resultVO.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/studentEdit", method = RequestMethod.POST)
	public CommonMessageResultVO studentEdit(RedirectAttributes redirectAttributes, @Valid ExamUserVO user, BindingResult result){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
		if(result.hasErrors()){
			List<ObjectError> errorList = result.getAllErrors();
			for(ObjectError error : errorList){
				FieldError fe = (FieldError) error;
				messageMap.put(fe.getField(), fe.getDefaultMessage());
			}
			resultVO.setMessageMap(messageMap);
			return resultVO;
		}
		try{
			user.setPassword(user.getUserId());
			user.setLastLockTime(new java.sql.Date(System.currentTimeMillis()));
			user.setLoginFailCount(0);
			userService.editUser(user);
			resultVO.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/deleteStudent", method = RequestMethod.POST)
	public CommonMessageResultVO deleteStudent(String userId){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
		try{
			userService.deleteUser(userId);
			resultVO.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
	}
	
	@RequestMapping(value = "/edit/{userId}", method = RequestMethod.POST)
	public String edit(RedirectAttributes redirectAttributes, ExamUserVO user, @PathVariable String userId){
		try{
			user.setGender(user.getGender().substring(0,1));
			user.setPassword(user.getUserId());
			user.setEmail("123456@qq.com");
			user.setLastLockTime(new java.sql.Date(System.currentTimeMillis()));
			user.setLoginFailCount(0);
			userService.editUser(user);
			redirectAttributes.addFlashAttribute("message", "修改成功");
		}catch(Exception e){
			e.printStackTrace();
			return "error";
		}
		return "redirect:/users";
	}
	
	@ResponseBody
	@RequestMapping(value = "/getStudentById", method = RequestMethod.POST)
	public ExamUserVO getStudentById(String userId){
		ExamUserVO vo = null;
		try {
			vo = userService.getUserById(userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vo;
	}
	
	@RequestMapping(value = "/edit/{userId}", method = RequestMethod.GET)
	public String toEdit(Model model, @PathVariable String userId) throws Exception{
		ExamUserVO user = userService.getUserById(userId);
		model.addAttribute("user", user);
		return "user/edit";
	}
	
	@RequestMapping(value = "/delete/{userId}", method = RequestMethod.GET)
	public String delete(RedirectAttributes redirectAttributes, @PathVariable String userId) {
		try {
			userService.deleteUser(userId);
			redirectAttributes.addFlashAttribute("message", "删除成功");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", "删除失败");
			e.printStackTrace();
		}
		return "redirect:/users";
	}
	
	@RequestMapping(value = "/checkID", method = RequestMethod.POST)
	public void checkID(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		boolean falg;
		try {
			if(userService.getUserById(id) == null){
				falg = true;
			}else{
				falg = false;
			}
			JSONObject json = new JSONObject();
			json.put("falg", falg);
			PrintWriter out = response.getWriter();
			out.write(json.toString());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
